package files;

import lombok.extern.java.Log;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
 * Created with Intel IDEA.
 *
 * @Auther: gjt
 * @Date: 2024/10/25 22:21
 */

@Log
public class ReadUpdateTask implements Runnable {
    private File File;

    private String ThreadName;


    public ReadUpdateTask(File file, String ThreadName) {
        this.File = file;
        this.ThreadName = ThreadName;
    }

    @Override
    public void run() {
        try (FileInputStream in = new FileInputStream(File);
             FileChannel fileChannel = in.getChannel();
        ) {
            // 获取文件共享锁
            FileLock fileLock = fileChannel.tryLock(0, Long.MAX_VALUE, true);

            if (null != fileLock && fileLock.isValid()) {
                XSSFWorkbook workbook = new XSSFWorkbook(in);

                
                System.out.println("线程" + ThreadName + "开始工作");
                Thread.sleep(10000);
            } else {
                log.warning("文件被锁住");
            }

            if (fileLock != null) {
                System.out.println( Thread.currentThread().getName()+ "工作结束释放文件锁");
                fileLock.release();
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
